package org.framework.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import org.framework.session.SessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.JdbcTransactionObjectSupport;
import org.springframework.transaction.TransactionDefinition;

import com.hiwan.platform.util.StackTraceUtil;
import com.hiwan.platform.utils.StringUtils;

//TODO　默认数据库　注入实现
public class HiwanDataSourceTransactionManager extends DataSourceTransactionManager{
	private static final long serialVersionUID = 1L;
	private static String DEFAULT_DBBASE = "ORACLE";
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Override
	protected void doBegin(Object transaction, TransactionDefinition definition) {
		super.doBegin(transaction, definition);
		JdbcTransactionObjectSupport txObject = (JdbcTransactionObjectSupport) transaction;
		ConnectionHolder holder = txObject.getConnectionHolder();
		setClientInfo(holder.getConnection());
	}
	private void setClientInfo(Connection connection) {
		if ("ORACLE".equals(DEFAULT_DBBASE)) {
			String menuId = SessionContext.getMenuId();
			if (StringUtils.isEmpty(menuId)) {
				menuId = "00000";
			}
			String userId = SessionContext.getUserId();
			String orgId = SessionContext.getOrgId();
			if (userId != null && orgId != null) {
				String clientInfo = "1|" + menuId + "|" + orgId + "|" + userId;
				CallableStatement stmt = null;
				try {
					String sql = "{ CALL dbms_application_info.set_client_info(?) }";
					stmt = connection.prepareCall(sql);
					stmt.setString(1, clientInfo);
					stmt.execute();
				} catch (SQLException e) {
					logger.error(StackTraceUtil.getStackTrace(e));
				} finally {
					if (stmt != null) {
						try {
							stmt.close();
						} catch (Exception ex) {
						}
					}
				}
			}
		}
	}
}
